const msgWrapper = require("../lib/utilx.js").msgWrapper;
const render = require("../instances/render");
const db = require("../models/index");
const Model = require("../models/index").models;
const Employee = Model.Employee;
const Record = Model.Record;
const Command = Model.Command;

var superagentPromisePlugin = require("superagent-promise-plugin");
require("es6-promise").polyfill();
var request = superagentPromisePlugin.patch(require("superagent"));
var charset = require("superagent-charset");
charset(request);

module.exports = (router) => {
    /**
     * 设备创建接口
     */
    router.post("/uploadFingerPrint", function *(){
        var ctx = this;
        ctx.checkBody("fingerprint").notEmpty();
        ctx.checkBody("psk").notEmpty();

        var fingerprint = Buffer.from(ctx.request.body.fingerprint).toString("base64");
        var psk = ctx.request.body.psk;

        var fingerprint_id = yield db.query("SELECT max(fingerprint_id) as 'max' FROM Employees",{
            type: db.QueryTypes.SELECT
        });
        fingerprint_id = fingerprint_id[0]["max"] + 1;      // null + 1 == NaN
        if(isNaN(fingerprint_id)){
            fingerprint_id = 1;
        }

        // 有旧的则删掉
        var employee = yield Employee.findOne({
            where : {
                psk,
                state : 0
            }
        });
        if(employee){
            yield employee.destroy();
        }

        // 如果指纹或指纹id与已创建的重复，则创建失败
        employee = yield Employee.findOne({
            where : {
                $or : [{
                    fingerprint,
                },{
                    fingerprint_id
                }],
                state : 1
            }
        });
        if(employee){
            ctx.body = msgWrapper("指纹或指纹Id已使用，创建失败",true,45);
            return;
        }

        // 创建新的员工指纹记录
        yield Employee.create({
            fingerprint,
            psk,
            state : 0,
            fingerprint_id
        });
        ctx.body = msgWrapper({
            fingerprint_id
        });

    });

    /**
     * 手机创建接口
     */
    router.post("/uploadUserInfo", function *(){
        var ctx = this;
        ctx.checkBody("name").notEmpty();
        ctx.checkBody("employee_id").notEmpty();
        ctx.checkBody("phone").notEmpty();
        ctx.checkBody("psk").notEmpty();

        var body = ctx.request.body;
        var name = body.name;
        var employee_id = body.employee_id;
        var phone = body.phone;
        var psk = body.psk;

        if(! /^\d{11}$/.test(phone)){
            ctx.body = msgWrapper("手机号格式不正确",true,49);
            return;
        }
        if(yield Employee.findOne({
                where : {
                    employee_id
                }
            })){
            ctx.body = msgWrapper("工号重复",true,50);
            return;
        }

        // psk + state(0)的只允许有一个
        var employee = yield Employee.findOne({
            where : {
                psk,
                state : 0
            }
        });
        if(employee){
            yield Employee.update({
                name,
                employee_id,
                phone,
                state : 1
            },{
                where : {
                    psk,
                    state : 0
                }
            });
            ctx.body = msgWrapper({});
            return;

        }else{
            ctx.body = msgWrapper("设备尚未录入指纹，请先在设备上录入指纹",1,44);
            return;
        }
    });

    /**
     * @return
     * employee_id
     * time
     * command(working)
     */
    router.post("/heartbeat", function*(){
        var ctx = this;
        ctx.checkBody("psk").notEmpty();

        var psk = ctx.request.body.psk;

        // 目前的设备命令
        var command = yield Command.findOne({
            where : {
                psk
            }
        });
        var command_text;
        if(command){
            command_text = command.dataValues.text;
            // 重改成working状态，上一次的状态会下发 todo：加一个确认措施会更好
            if(command_text !== "working"){
                yield Command.update({
                    text : "working",
                    data : JSON.stringify({})
                },{
                    where : {
                        psk : command.psk
                    }
                });
            }
        }else{
            ctx.body = msgWrapper("psk未注册",true,47);
            return;
        }

        // 最新的变更时间
        var employee = yield Employee.findOne({
            order:[["updatedAt","DESC"]],
            state : 1
        });
        if(!employee){
            ctx.body = msgWrapper("当前数据库内没有用户",true,48);
            return;
        }
        var d = new Date();

        ctx.body = msgWrapper({
            lasted_modified_time : new Date(employee.updatedAt).getTime().toString(),     // 最新的员工数据库变更时间
            time_now : d.getTime().toString(),
            command : command_text,
            data: JSON.parse(command.data)
        });
    });

    /**
     * native_lasted_modified_time
     */
    router.post("/completeData", function*(){
        var ctx = this;
        ctx.checkBody("native_lasted_modified_time").notEmpty();

        var native_lasted_modified_time = ctx.request.body.native_lasted_modified_time;

        // 本地没有，从1开始
        var employee = yield Employee.findOne({
            where : {
                updatedAt : {
                    $gt: new Date(parseInt(native_lasted_modified_time))      // todo
                },
                state : 1
            },
            order : [["updatedAt","ASC"]],
            attributes : {
                exclude : ["id","name","phone","employee_id","state","psk","isValid","createdAt"]
            }
        });
        if(!employee){
            ctx.body = msgWrapper("当前数据库内没有用户",true,48);
            return;
        }
        employee.fingerprint = Buffer.from(employee.fingerprint,"base64");
        employee.dataValues.native_lasted_modified_time = new Date(employee.updatedAt).getTime().toString();
        delete employee.dataValues.updatedAt;
        ctx.body = msgWrapper({
            employee
        });
    });

    /**
     * fingerprint_id
     * clock_time : unix时间戳
     */
    router.post("/clockInAndOut", function*(){
        var ctx = this;
        ctx.checkBody("fingerprint_id").notEmpty().toInt();
        ctx.checkBody("clock_time").notEmpty();          // todo： 为clock_time加密

        var fingerprint_id = ctx.request.body.fingerprint_id;
        var clock_time = new Date(parseInt(ctx.request.body.clock_time));

        var t = new Date();
        t.setUTCHours(0,0,0);
        var day = clock_time.getDate();
        if(isNaN(day) || day !== t.getDate()){
            // code: 42 非当天日期
            ctx.body = msgWrapper("日期不合法，非当天日期",1,42);
            return;
        }

        var employee = yield Employee.findOne({
            where : {
                fingerprint_id,
                state : 1
            }
        });
        if(!employee || employee.state !== 1){
            ctx.body = msgWrapper("打卡失败，此用户不存在",1,43);
            return;
        }

        var record = yield Record.findOne({
            where : {
                EmployeeId : employee.id,
                createdAt: {
                    $gte: t
                }
            },
            order: [["createdAt","DESC"]]
        });
        var isClockOut = record && (record.type === 1);
        yield Record.create({
            type : isClockOut ? 0 : 1,
            EmployeeId : employee.id
        });
        ctx.body = msgWrapper({});
    });


    router.post("/deleteFingerprint", function*() {
        var ctx = this;
        ctx.checkBody("fingerprint_id").notEmpty().toInt();
        var fingerprint_id =  ctx.request.body.fingerprint_id;

        var employee = yield Employee.findOne({
            where : {
                fingerprint_id
            }
        });
        if(!employee){
            ctx.body = msgWrapper("数据库内没有此指纹id对应的用户",true,46);
            return;
        }

        // 更新传给设备的Command
        yield Command.update({
            text : "delete",
            data : JSON.stringify({
                fingerprint_id
            })
        },{
            where : {
                psk : employee.psk
            }
        });

        yield Employee.update({
            isValid : 0
        },{
            where : {
                id : employee.id
            }
        });

        ctx.body = msgWrapper({});
    });

    router.get("/getAllRecords", function *(){
        var ctx = this;

        var records = yield Record.findAll({
            include : {
                model : Employee
            },
            order : [["createdAt","DESC"]]
        });
        ctx.body = msgWrapper(records);
    });

    router.post("/searchEmployee", function*(){
        var ctx = this;
        var body = ctx.request.body;

        var employee_id = body.employee_id;
        var name = body.name;
        var employee;
        if(employee_id || name){
            if(employee_id){
                employee = yield Employee.findOne({
                    where : {
                        employee_id
                    }
                });
            }else{
                employee = yield Employee.findOne({
                    where : {
                        name
                    }
                });
            }

            if(employee){
                ctx.body = msgWrapper({
                    id : employee.id
                });
                return;
            }
        }

        ctx.body = msgWrapper("没有此员工",true,61);
    });


    // 不能用重定向，要直接是那个页面，否则微信会判定为没有权限
    router.get("/smartconfig", function *(){
        var ctx = this;
        // https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
        // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        var appid = "wx2a51c89f0856c17e";
        var appsecret = "f4fe1ff67a27d4d618d63353917e1e4d";

        var res = yield request
            .get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`);
        var data = JSON.parse(res.text);
        var access_token = data.access_token;

        res = yield request
            .get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`);
        data = JSON.parse(res.text);

        var ticket = data.ticket;
        var timestamp = parseInt(new Date().getTime().toString().slice(0,10));
        var noncestr = "Gi4YHdadQa11KyZe";

        ctx.body = yield render("smartconfig.html",{
            ticket,
            timestamp,
            noncestr,
            appid
        });
    });
};